package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QueryEnv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public QueryEnv() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		String strSQL = "";
		ResultTableSet resultTableSet = new ResultTableSet();
		String fromCall = request.getParameter("fc");
		
		if ("raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
			strSQL = "SELECT COUNT(*) FROM env WHERE bssid=?";
		} else {
			strSQL = "SELECT COUNT(*) FROM env WHERE bssid=? AND subsysid=?";
		}
		
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		final String bssId ="MBMS";
		
		int total_pages = 1;
		int count  = 0; 
		int page = 1;
		int limit = 10;
		
		if ("".equalsIgnoreCase(sidx)|| sidx==null) {
			sidx = "envname";
		} 
		if ("".equalsIgnoreCase(sord)|| sord==null) {
			sord = "ASC";
		} else {
			page = Integer.parseInt(request.getParameter("page"));
			limit = Integer.parseInt(request.getParameter("rows"));
		}
		
		String subSysId = request.getParameter("subSysId");
		
		try {
			conn = wid.getConn(true);	
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, bssId);
			if (!"raiseDeplyByDelivery".equalsIgnoreCase(fromCall) && !"reDep".equalsIgnoreCase(fromCall)) {
				ps.setString(2, subSysId);	
			}
			
			rs = ps.executeQuery();
			rs.next();
			count  = rs.getInt(1);
			
			if ( count  != 0 ) {
				
				if (limit  < count) {
					total_pages = (count / limit)+1;	
				}
				if ("raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
					strSQL = "SELECT DISTINCT envid, envname FROM env WHERE bssid=?";
				} else {
					if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
						strSQL = "SELECT t1.envid,t1.envname,t1.selfClass,t1.preClass,t1.creator, t1.createdDateTime FROM env t1 WHERE t1.bssid=? AND t1.subsysid=?  ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
					} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.envid,t1.envname,t1.webconsolesn AS wcsn,t1.selfClass,t1.preClass,t1.creator, t1.createdDateTime,t2.webconsoleip AS wcip FROM env t1,OUTER wcl t2 WHERE t1.bssid=? AND t1.subsysid=? AND t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.webconsolesn=t2.webconsolesn ORDER BY "+sidx+" "+sord;
					}
				}
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, bssId);
				if (!"raiseDeplyByDelivery".equalsIgnoreCase(fromCall) && !"reDep".equalsIgnoreCase(fromCall)) {
					ps.setString(2,subSysId);
				}
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();
				
				while ( rs.next() ) {
					String envid = rs.getString("envid");
					
					if ("selEnvBySubSys".equalsIgnoreCase(fromCall) ||"mappingSquadHost".equalsIgnoreCase(fromCall) ||"mappingEnvSquad".equalsIgnoreCase(fromCall) || "raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
						InfoStruc infoStruc = new InfoStruc();
						infoStruc.setId(rs.getString("envid"));
						infoStruc.setName( wid.DB2UI( rs.getString("envname"),conn.getMetaData().getDatabaseProductName() ) );
						infoStrucs.add(infoStruc);
					}  else {
						Rows row = new Rows();
						row.setId(envid);
						String[] cell = new String[5];
						cell[0] = envid;
						cell[1] = wid.DB2UI( rs.getString("envname"),conn.getMetaData().getDatabaseProductName() );
						cell[2] = rs.getString("wcip")==null?"無設定":rs.getString("wcip");
						cell[3] = String.valueOf( rs.getInt("selfClass") ) ;
						cell[4] = String.valueOf( rs.getInt("preClass") ) ;
						
						row.setCell(cell);
						rows.add(row);	
					}
				}
				resultTableSet.setRows( rows );
				resultTableSet.setPage( String.valueOf(page) );
				resultTableSet.setTotal( total_pages );
				resultTableSet.setRecords( String.valueOf(count) );
				
			} else {
				page =0;
				total_pages=0;
				resultTableSet.setPage( String.valueOf(page) );
				resultTableSet.setTotal( total_pages );
				resultTableSet.setRecords( String.valueOf(count) );
			}
		} catch ( UnsupportedEncodingException e ) {
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch ( SQLException e) {
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch ( Exception e) {
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		if ("selEnvBySubSys".equalsIgnoreCase(fromCall) || "mappingSquadHost".equalsIgnoreCase(fromCall) ||"mappingEnvSquad".equalsIgnoreCase(fromCall) || "raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
			response.getWriter().write(new Gson().toJson(infoStrucs));
		} else {
			response.getWriter().write(new Gson().toJson(resultTableSet));	
		}
	}
}